/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.zhuangfei.ohos_timetableview.slice;

import com.zhuangfei.ohos_timetableview.ResourceTable;
import com.zhuangfei.ohos_timetableview.adapter.NonViewAdapter;
import com.zhuangfei.ohos_timetableview.base.BaseAbilitySlice;
import com.zhuangfei.ohos_timetableview.model.SubjectRepertory;
import com.zhuangfei.ohos_timetableview.spinner.MaterialSpinner;
import com.zhuangfei.timetable.model.Schedule;
import com.zhuangfei.timetable.model.ScheduleSupport;

import ohos.aafwk.content.Intent;
import ohos.agp.components.ListContainer;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;

import java.util.ArrayList;
import java.util.List;

/**
 * NonViewSlice
 *
 * @since 2021-03-29
 */
public class NonViewSlice extends BaseAbilitySlice {
    private static final String[] SPIN_MUNE = {"全部课程", "第1周有课的课程", "第1周星期一有课的课程"};

    List<Schedule> schedules;
    ListContainer listView;
    NonViewAdapter adapter;
    Intent intents;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_non_view);
        initViews();
        intents = intent;
    }

    private void initViews() {
        showPopmenu();

        schedules = new ArrayList<>();
        listView = (ListContainer) findComponentById(ResourceTable.Id_id_listview);
        adapter = new NonViewAdapter(this, schedules);
        listView.setItemProvider(adapter);
        requestData();
    }

    /**
     * showPopmenu
     */
    public void showPopmenu() {
        MaterialSpinner spinner = (MaterialSpinner) findComponentById(ResourceTable.Id_id_more);
        spinner.setOnItemSelectedListener((MaterialSpinner.OnItemSelectedListener<String>) (
                view, position, id, item) -> {
            selectLayout(position);
            spinner.setShowFalse();
        });
        spinner.setItems(SPIN_MUNE);
        spinner.setOnNothingSelectedListener(spinner1 -> spinner1.setShowFalse());
    }

    private void selectLayout(int position) {
        switch (position) {
            case 0:
                all();
                break;
            case 1:
                haveTime();
                break;
            case 2:
                haveTimeWithMonday();
                break;
            default:
                break;
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    /**
     * 获取所有课程
     */
    protected void all() {
        schedules.clear();
        schedules.addAll(getData());
        adapter.notifyDataChanged();
    }

    /**
     * 获取第一周有课的课程并显示出来
     */
    protected void haveTime() {
        List<Schedule> result = new ArrayList<>();
        List<Schedule>[] arr = ScheduleSupport.splitSubjectWithDay(getData());
        for (int i = 0; i < arr.length; i++) {
            List<Schedule> tmpList = arr[i];
            for (Schedule schedule : tmpList) {
                if (ScheduleSupport.isThisWeek(schedule, 1)) {
                    result.add(schedule);
                }
            }
        }
        schedules.clear();
        schedules.addAll(result);
        adapter.notifyDataChanged();
    }

    /**
     * 显示第一周周一有课的课程
     */
    protected void haveTimeWithMonday() {
        List<Schedule> tmpList = ScheduleSupport.getHaveSubjectsWithDay(
                getData(), 1, 0);
        schedules.clear();
        schedules.addAll(tmpList);
        adapter.notifyDataChanged();
    }

    /**
     * getData
     *
     * @return 数据集
     */
    public List<Schedule> getData() {
        List<Schedule> list = ScheduleSupport.transform(SubjectRepertory.loadDefaultSubjects());
        list = ScheduleSupport.getColorReflect(list);
        return list;
    }

    EventHandler runner = new EventHandler(EventRunner.create()) {
        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            NonViewSlice.this.getUITaskDispatcher().asyncDispatch(() -> {
                all();
            });

        }
    };

    /**
     * 2秒后刷新界面，模拟网络请求
     */
    private void requestData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500);

                } catch (InterruptedException e) {
                    String errorString = e.toString();
                }
                runner.sendEvent(InnerEvent.get());
            }
        }).start();
    }
}
